package com.yc.spring.mvc.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class HandleResponse {
	/**
	 * 处理静态资源的方法
	 * @param response
	 * @param url
	 * @throws IOException 
	 */
	protected static void handlerStaticResource(HttpServletResponse response, String url) throws IOException {
		File fl = new File(url);
		
		//System.out.println(fl);
		
		if(!fl.exists() || !fl.isFile()) {
			send404(response, url);
			return;
		}
		
		try(FileInputStream fis = new FileInputStream(fl)){
			byte[] bt = new byte[fis.available()];
			fis.read(bt);
			sendData(response, bt);
		}
	}

	private static void sendData(HttpServletResponse response, byte[] bt) throws IOException {
		ServletOutputStream sos = response.getOutputStream();
		sos.write(bt);
		sos.flush();
	}

	private static void send404(HttpServletResponse response, String url) throws IOException {
		PrintWriter out = response.getWriter();
		out.println("<h1>HTTP/1.1 404 File Not Found! - " + url + "<h1>");
		out.flush();
	}
	
	protected static void sendJson(HttpServletResponse response, Object obj) throws IOException {
		PrintWriter out = response.getWriter();
		Gson gson = new GsonBuilder().serializeNulls().create();
		out.print(gson.toJson(obj));
		out.flush();
	}
}
